from flask import Flask, request, send_file
import subprocess
import os

app = Flask(__name__)


@app.route('/convert2', methods=['POST'])
def convert_to_pdf():
    data = request.json
    url = data.get('url')

    if not url:
        return {"error": "URL is required"}, 400

    try:
        # 调用 Puppeteer 脚本生成 PDF
        pdf_path = 'output.pdf'
        script = f"""
        const puppeteer = require('puppeteer');
        (async () => {{
            const browser = await puppeteer.launch();
            const page = await browser.newPage();
            await page.goto('{url}', {{ waitUntil: 'networkidle2' }});
            await page.pdf({{ path: '{pdf_path}', format: 'A4' }});
            await browser.close();
        }})();
        """

        with open('generate_pdf.js', 'w') as f:
            f.write(script)

        # 运行 Puppeteer 脚本
        subprocess.run(['node', 'generate_pdf.js'])

        return send_file(pdf_path, as_attachment=True)

    except Exception as e:
        return {"error": str(e)}, 500


if __name__ == '__main__':
    app.run(debug=True)
